#include <cassert>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <sys/socket.h>

#include "../include/db_connection_pool.h"
#include "../include/http_conn.h"
#include "../include/locker.h"
#include "../include/log.h"
#include "../include/threadpool.h"
#include "../include/time_heap.h"
#include "../include/utils.h"

#define MAX_FD 65536
#define MAX_EVENT_NUM 10000
#define TIMESLOT 5 // 最小超时单位

/*********** 配置文件 **********/

static UTILS::IniHelper confFile("./server.conf");

#define GET_CONF_STR(SECTION, KEY, DVALUE) std::string(confFile.getIniConfig(SECTION, KEY, DVALUE)).c_str()

/*********** 事件触发选项 **********/

#ifdef ET_MODE
#define LISTENFD_ET
#elif LT_MODE
#define LISTENFD_LT
#else
#define LISTENFD_ET
#endif

/*********** 同步日志选项 **********/

// 同步写日志
// #define SYNLOG

// 异步写日志
#define ASYNLOG

/*********** 定时器相关 **********/

static int pipefd[2];
static time_heap tmheap(1024);
static int epollfd = 0;

/// @brief 定时处理任务
/// @note 重新定时以不断触发SIGALRM信号
void timer_handler()
{
    tmheap.tick();
    heap_timer *top_timer = tmheap.top();
    // 空堆
    if (top_timer == nullptr)
        // 间隔时间固定
        alarm(TIMESLOT);
    else
    {
        time_t cur = time(NULL);
        // 间隔时间为堆顶定时器到期时间
        alarm(top_timer->expire - cur);
    }
}

/// @brief 定时器回调函数
/// @note 删除并关闭非活动连接在socket上的注册事件
/// @param user_data
void cb_func(client_data *user_data)
{
    // 删除非活动连接在Socket上的注册事件
    epoll_ctl(epollfd, EPOLL_CTL_DEL, user_data->sockfd, 0);
    assert(user_data);

    // 关闭FD并减少计数
    close(user_data->sockfd);
    http_conn::m_user_count--;

    LOG_INFO("Close FD: %d", user_data->sockfd);
    Log::getInstance()->flush();
}

/*********** 辅助函数 **********/

extern int addFd(int epollfd, int fd, bool one_shot);
extern int removeFd(int epollfd, int fd);
extern int setNonblocking(int fd);

/// @brief 设置信号函数
/// @param sig
/// @param handler
/// @param restart
void addSig(int sig, void(handler)(int), bool restart = true)
{
    struct sigaction sa;
    memset(&sa, '\0', sizeof(sa));
    // 信号处理函数中仅仅发送信号值，不做对应逻辑处理
    sa.sa_handler = handler;
    if (restart)
        sa.sa_flags |= SA_RESTART;
    // 将所有信号添加到信号集中，即在信号处理函数运行期间屏蔽所有信号
    sigfillset(&sa.sa_mask);
    assert(sigaction(sig, &sa, NULL) != -1);
}

/// @brief 信号处理函数
/// @param sig
void sig_handler(int sig)
{
    int save_errno = errno;
    int msg = sig;
    // 将信号（字符类型）写入管道
    send(pipefd[1], (char *)&msg, 1, 0);
    errno = save_errno;
}

void show_error(int connfd, const char *info)
{
    printf("%s", info);
    send(connfd, info, strlen(info), 0);
    close(connfd);
}

/*********** 主入口函数 **********/

int main(int argc, const char *argv[])
{
    if (argc <= 2)
    {
        printf("Usage: %s [ip_address] [port_number]", argv[0]);
        return 1;
    }

#ifdef ET_MODE
    fprintf(stdout, "[RUNING FOR ET MODE]\n");
#elif LT_MODE
    fprintf(stdout, "[RUNING FOR LT MODE]\n");
#else
    fprintf(stdout, "[DEFAULT ET MODE]\n");
#endif

#ifdef ASYNLOG
    // 异步日志模型
    Log::getInstance()->init(GET_CONF_STR("LOG", "logfile", "./log/ServerLog"), 2000, 800000, 8);
#endif

#ifdef SYNLOG
    // 同步日志模型
    Log::getInstance()->init(GET_CONF_STR("LOG", "logfile", "./log/ServerLog"), 2000, 800000, 0);
#endif

    const char *IP = argv[1];
    const int PORT = atoi(argv[2]);
    int ret = 0;

    // 忽略SIGPIPE信号
    addSig(SIGPIPE, SIG_IGN);

    db_connection_pool *connPool = db_connection_pool::GetInstance(GET_CONF_STR("DB", "url", "tcp://localhost:3306"),
                                                                   GET_CONF_STR("DB", "user", "root"),
                                                                   GET_CONF_STR("DB", "password", ""),
                                                                   GET_CONF_STR("DB", "dbname", "test"),
                                                                   atoi(GET_CONF_STR("DB", "port", "3306")),
                                                                   atoi(GET_CONF_STR("DB", "maxconn", "20")));

    // 创建线程池
    threadpool<http_conn> *pool = NULL;
    try
    {
        pool = new threadpool<http_conn>(connPool);
    }
    catch (...)
    {
        return 1;
    }

    // 为客户连接预分配http_conn对象
    http_conn *users = new http_conn[MAX_FD];
    assert(users);

    // 初始化数据库表
    users->initmysql_result(connPool);

    int listenfd = socket(PF_INET, SOCK_STREAM, 0);
    assert(listenfd >= 0);

    // 阻止TIME_WAIT状态
    // linger tmp{1, 0};
    // setsockopt(listenfd, SOL_SOCKET, SO_LINGER, &tmp, sizeof(tmp));

    // 如果端口忙，但TCP状态位于 TIME_WAIT ，可以重用端口
    int flag = 1;
    setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));

    sockaddr_in address;
    memset(&address, 0, sizeof(address));
    address.sin_addr.s_addr = inet_addr(IP);
    address.sin_family = AF_INET;
    address.sin_port = htons(PORT);
    ret = bind(listenfd, (sockaddr *)&address, sizeof(address));
    assert(ret >= 0);
    ret = listen(listenfd, 5);
    assert(ret >= 0);

    epoll_event events[MAX_EVENT_NUM];
    int epollfd = epoll_create(5);
    assert(epollfd != -1);
    addFd(epollfd, listenfd, false);
    http_conn::m_epollfd = epollfd;

    // 创建管道
    ret = socketpair(PF_UNIX, SOCK_STREAM, 0, pipefd);
    assert(ret != -1);
    setNonblocking(pipefd[1]);
    addFd(epollfd, pipefd[0], false);
    addSig(SIGALRM, sig_handler, false);
    addSig(SIGTERM, sig_handler, false);

    // 用户定时器列表
    client_data *users_timer = new client_data[MAX_FD];
    alarm(TIMESLOT);

    bool timeout = false;
    bool stop_server = false;
    while (!stop_server)
    {
        int num = epoll_wait(epollfd, events, MAX_EVENT_NUM, -1);
        if ((num < 0) && (errno != EINTR))
        {
            LOG_ERROR("%s", "Main - Epoll Failure.");
            printf("Epoll Failure\n");
            break;
        }
        for (int i = 0; i < num; ++i)
        {
            int sockfd = events[i].data.fd;
            // 新到的客户连接
            if (sockfd == listenfd)
            {
                sockaddr_in client_addr;
                socklen_t client_addrlen = sizeof(client_addr);

#ifdef LISTENFD_LT
                int connfd = accept(listenfd, (sockaddr *)&client_addr, &client_addrlen);
                if (connfd < 0)
                {
                    LOG_ERROR("Accept - Error is: %d", errno);
                    perror("Accept");
                    continue;
                }
                if (http_conn::m_user_count >= MAX_FD)
                {
                    LOG_ERROR("%s", "Internal Server Busy");
                    show_error(connfd, "Internal Server Busy");
                    continue;
                }
                // 初始化客户连接
                users[connfd].init(connfd, client_addr);

                // 初始化客户数据
                users_timer[connfd].address = client_addr;
                users_timer[connfd].sockfd = connfd;
                // 创建定时器，并初始化
                heap_timer *timer = new heap_timer(time(NULL) + 3 * TIMESLOT, &users_timer[connfd], cb_func);
                users_timer[connfd].timer = timer;
                // 添加定时器
                tmheap.add_timer(timer);
#endif

#ifdef LISTENFD_ET
                while (1)
                {
                    int connfd = accept(listenfd, (struct sockaddr *)&client_addr, &client_addrlen);
                    if (connfd < 0)
                    {
                        LOG_ERROR("Accept - Error is: %d", errno);
                        break;
                    }
                    if (http_conn::m_user_count >= MAX_FD)
                    {
                        show_error(connfd, "Internal Server Busy");
                        LOG_ERROR("%s", "Internal Server Busy");
                        break;
                    }
                    users[connfd].init(connfd, client_addr);

                    // 初始化client_data数据
                    users_timer[connfd].address = client_addr;
                    users_timer[connfd].sockfd = connfd;

                    // 创建定时器，并初始化
                    heap_timer *timer = new heap_timer(time(NULL) + 3 * TIMESLOT, &users_timer[connfd], cb_func);
                    users_timer[connfd].timer = timer;
                    // 添加定时器
                    tmheap.add_timer(timer);
                }
                continue;
#endif
            }
            // 若出现异常/服务器端关闭连接，则关闭此连接，移除该定时器（回调处理）
            else if (events[i].events & (EPOLLHUP | EPOLLRDHUP | EPOLLERR))
            {
                heap_timer *timer = users_timer[sockfd].timer;
                timer->cb_func(&users_timer[sockfd]);
                if (timer)
                    tmheap.del_timer(timer);
            }
            // 信号处理
            else if ((sockfd == pipefd[0]) && (events[i].events & EPOLLIN))
            {
                int sig;
                char signals[1024];
                ret = recv(pipefd[0], signals, sizeof(signals), 0);
                if (ret == -1)
                    continue;
                else if (ret == 0)
                    continue;
                else
                {
                    for (int i = 0; i < ret; ++i)
                    {
                        switch (signals[i])
                        {
                        case SIGALRM:
                            timeout = true;
                            break;
                        case SIGTERM:
                            stop_server = true;
                        }
                    }
                }
            }
            // 处理客户连接上接收到的数据，根据读的结果，决定是否将该连接任务加入线程池还是关闭连接
            else if (events[i].events & EPOLLIN)
            {
                heap_timer *timer = users_timer[sockfd].timer;
                if (users[sockfd].read())
                {
                    LOG_INFO("Deal With The Client (%s)", inet_ntoa(users[sockfd].get_address()->sin_addr));
                    Log::getInstance()->flush();
                    // 监测到读事件，将该事件放入请求队列
                    pool->append(users + sockfd);
                    // 若有数据传输，将定时器往后延续3个单位
                    if (timer)
                    {
                        timer->expire = time(NULL) + 3 * TIMESLOT;
                        LOG_INFO("%s", "Adjust Timer Once");
                        Log::getInstance()->flush();
                        // 调整目标定时器位置
                        tmheap.adjust_timer(timer);
                    }
                }
                else
                {
                    // 若发生读错误/对方关闭连接，则服务器也关闭连接并删除定时器
                    timer->cb_func(&users_timer[sockfd]);
                    if (timer)
                        tmheap.del_timer(timer);
                }
            }
            // 处理往客户连接上写入数据，根据写的结果，决定是否将该连接任务关闭连接
            else if (events[i].events & EPOLLOUT)
            {
                heap_timer *timer = users_timer[sockfd].timer;
                if (users[sockfd].write())
                {
                    LOG_INFO("Send Data To The Client (%s)", inet_ntoa(users[sockfd].get_address()->sin_addr));
                    Log::getInstance()->flush();
                    // 若有数据传输，将定时器往后延续3个单位
                    if (timer)
                    {
                        timer->expire = time(NULL) + 3 * TIMESLOT;
                        LOG_INFO("%s", "Adjust Timer Once");
                        Log::getInstance()->flush();
                        // 调整目标定时器位置
                        tmheap.adjust_timer(timer);
                    }
                }
                else
                {
                    // 若发生读错误/对方关闭连接，则服务器也关闭连接并删除定时器
                    timer->cb_func(&users_timer[sockfd]);
                    if (timer)
                        tmheap.del_timer(timer);
                }
            }
            else
            {
                // TODO
            }
        }
        // 处理定时器事件（IO事件优先级高）
        if (timeout)
        {
            timer_handler();
            timeout = false;
        }
    }

    close(epollfd);
    close(listenfd);
    close(pipefd[1]);
    close(pipefd[0]);

    delete[] users;
    delete[] users_timer;
    delete pool;
    return 0;
}
